package com.ititer.web.controller;

import java.util.Date;


import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;

import com.ititer.bean.AccountBean;
import com.ititer.enums.LoginState;
import com.ititer.model.Account;
import com.ititer.result.LoginResult;
import com.ititer.web.abs.AbstractController;
import com.ititer.web.cookie.Cookier;

@Resource
public class Login extends AbstractController {

	@Get
	@Path({ "/login" })
	public void form() {
		setPageTitle("Login to Ititer ~ ");
	}

	@Get
	@Path({ "/logout" })
	public void logout() {
		removeSession();
		controllerResult.redirectTo(Login.class).form();
	}

	@Post
	@Path({ "/login" })
	public void doLogin(AccountBean account) {
		setPageTitle("Logining now ~");
		account.setIp(getIp());
		account.setReferer(getReferer());
		account.setLastLoginTime(new Date());

		validate(account).onErrorRedirectTo(Login.class).form();
		LoginResult result = accountSvc.login(account);
		LoginState state = result.getState();

		switch (state) {
		case AccountNotExist:
			setErrorMessage("account.not.exist", account.getEmail());
			controllerResult.redirectTo(Login.class).form();
			break;
		case PasswordError:
			setErrorMessage("password.is.wrong");
			controllerResult.redirectTo(Login.class).form();
			break;
		case Success:
			Account logedAccount = result.getAccount();
			//save cookie
			Cookier.createCookie(response, logedAccount);
			//save session
			saveSession(logedAccount);
			controllerResult.redirectTo(My.class).home();
			//			controllerResult.forwardTo(My.class).home();
			break;
		default:
			controllerResult.redirectTo(Error.class).info();
		}
	}
}
